<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3D场景性能测试</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background: #000;
            color: #fff;
            font-family: Arial, sans-serif;
            overflow: hidden;
        }
        
        #performance-panel {
            position: fixed;
            top: 10px;
            left: 10px;
            background: rgba(0, 0, 0, 0.8);
            padding: 15px;
            border-radius: 8px;
            z-index: 1000;
            min-width: 250px;
        }
        
        .metric {
            margin: 5px 0;
            display: flex;
            justify-content: space-between;
        }
        
        .metric-label {
            color: #ccc;
        }
        
        .metric-value {
            color: #0f0;
            font-weight: bold;
        }
        
        .metric-value.warning {
            color: #ff0;
        }
        
        .metric-value.critical {
            color: #f00;
        }
        
        #controls {
            position: fixed;
            top: 10px;
            right: 10px;
            background: rgba(0, 0, 0, 0.8);
            padding: 15px;
            border-radius: 8px;
            z-index: 1000;
        }
        
        button {
            background: #333;
            color: #fff;
            border: 1px solid #555;
            padding: 8px 12px;
            margin: 2px;
            border-radius: 4px;
            cursor: pointer;
        }
        
        button:hover {
            background: #555;
        }
        
        button.active {
            background: #0a84ff;
        }
        
        #main-container {
            width: 100vw;
            height: 100vh;
        }
    </style>
</head>
<body>
    <div id="performance-panel">
        <h3>性能监控</h3>
        <div class="metric">
            <span class="metric-label">FPS:</span>
            <span class="metric-value" id="fps">--</span>
        </div>
        <div class="metric">
            <span class="metric-label">帧时间:</span>
            <span class="metric-value" id="frame-time">--</span>
        </div>
        <div class="metric">
            <span class="metric-label">绘制调用:</span>
            <span class="metric-value" id="draw-calls">--</span>
        </div>
        <div class="metric">
            <span class="metric-label">三角形:</span>
            <span class="metric-value" id="triangles">--</span>
        </div>
        <div class="metric">
            <span class="metric-label">性能级别:</span>
            <span class="metric-value" id="performance-level">--</span>
        </div>
        <div class="metric">
            <span class="metric-label">阴影:</span>
            <span class="metric-value" id="shadows">--</span>
        </div>
        <div class="metric">
            <span class="metric-label">像素比:</span>
            <span class="metric-value" id="pixel-ratio">--</span>
        </div>
    </div>
    
    <div id="controls">
        <h3>性能控制</h3>
        <button id="toggle-shadows">切换阴影</button>
        <button id="toggle-adaptive">切换自适应</button>
        <button id="force-low">强制低质量</button>
        <button id="force-high">强制高质量</button>
        <button id="reset-performance">重置性能</button>
    </div>
    
    <div id="main-container"></div>

    <script type="module">
        import * as THREE from 'three';
        import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
        import { PerformanceManager } from './js/utils/PerformanceManager.js';
        import { ModelLoader } from './js/ModelLoader.js';

        class PerformanceTest {
            constructor() {
                this.scene = null;
                this.camera = null;
                this.renderer = null;
                this.controls = null;
                this.performanceManager = null;
                this.modelLoader = new ModelLoader();
                this.testObjects = [];
                
                this.init();
            }
            
            async init() {
                this.setupScene();
                this.setupLighting();
                await this.loadTestModels();
                this.setupPerformanceManager();
                this.setupControls();
                this.animate();
            }
            
            setupScene() {
                // 创建场景
                this.scene = new THREE.Scene();
                this.scene.background = new THREE.Color(0x87CEEB);
                
                // 创建相机
                this.camera = new THREE.PerspectiveCamera(
                    75,
                    window.innerWidth / window.innerHeight,
                    0.1,
                    1000
                );
                this.camera.position.set(0, 5, 10);
                
                // 创建渲染器
                this.renderer = new THREE.WebGLRenderer({ 
                    antialias: true,
                    alpha: true 
                });
                this.renderer.setSize(window.innerWidth, window.innerHeight);
                this.renderer.setPixelRatio(window.devicePixelRatio);
                this.renderer.shadowMap.enabled = true;
                this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
                this.renderer.outputColorSpace = THREE.SRGBColorSpace;
                
                document.getElementById('main-container').appendChild(this.renderer.domElement);
                
                // 创建控制器
                this.controls = new OrbitControls(this.camera, this.renderer.domElement);
                this.controls.enableDamping = true;
                this.controls.dampingFactor = 0.05;
                
                // 设置ModelLoader的renderer引用
                this.modelLoader.renderer = this.renderer;
            }
            
            setupLighting() {
                // 环境光
                const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
                this.scene.add(ambientLight);
                
                // 主方向光
                const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
                directionalLight.position.set(5, 10, 5);
                directionalLight.castShadow = true;
                directionalLight.shadow.mapSize.setScalar(1024);
                directionalLight.shadow.camera.near = 0.1;
                directionalLight.shadow.camera.far = 30;
                directionalLight.shadow.camera.left = -10;
                directionalLight.shadow.camera.right = 10;
                directionalLight.shadow.camera.top = 10;
                directionalLight.shadow.camera.bottom = -10;
                directionalLight.shadow.bias = -0.0001;
                this.scene.add(directionalLight);
                
                // 半球光
                const hemisphereLight = new THREE.HemisphereLight(0x87CEEB, 0x362d1d, 0.3);
                this.scene.add(hemisphereLight);
            }
            
            async loadTestModels() {
                // 创建测试几何体
                const geometries = [
                    new THREE.BoxGeometry(1, 1, 1),
                    new THREE.SphereGeometry(0.5, 32, 32),
                    new THREE.CylinderGeometry(0.5, 0.5, 1, 16),
                    new THREE.TorusGeometry(0.5, 0.2, 16, 100)
                ];
                
                // 创建测试材质
                const materials = [
                    new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 0.7, metalness: 0.1 }),
                    new THREE.MeshStandardMaterial({ color: 0x00ff00, roughness: 0.5, metalness: 0.3 }),
                    new THREE.MeshStandardMaterial({ color: 0x0000ff, roughness: 0.3, metalness: 0.7 }),
                    new THREE.MeshStandardMaterial({ color: 0xffff00, roughness: 0.8, metalness: 0.0 })
                ];
                
                // 创建多个测试对象
                for (let i = 0; i < 50; i++) {
                    const geometry = geometries[i % geometries.length];
                    const material = materials[i % materials.length].clone();
                    
                    // 优化材质
                    this.modelLoader.optimizeTextures(material);
                    
                    const mesh = new THREE.Mesh(geometry, material);
                    mesh.position.set(
                        (Math.random() - 0.5) * 20,
                        Math.random() * 5,
                        (Math.random() - 0.5) * 20
                    );
                    mesh.rotation.set(
                        Math.random() * Math.PI,
                        Math.random() * Math.PI,
                        Math.random() * Math.PI
                    );
                    mesh.castShadow = true;
                    mesh.receiveShadow = true;
                    
                    this.scene.add(mesh);
                    this.testObjects.push(mesh);
                }
                
                // 添加地面
                const groundGeometry = new THREE.PlaneGeometry(50, 50);
                const groundMaterial = new THREE.MeshStandardMaterial({ 
                    color: 0x808080,
                    roughness: 0.8,
                    metalness: 0.1
                });
                const ground = new THREE.Mesh(groundGeometry, groundMaterial);
                ground.rotation.x = -Math.PI / 2;
                ground.receiveShadow = true;
                this.scene.add(ground);
            }
            
            setupPerformanceManager() {
                this.performanceManager = new PerformanceManager(this.renderer, this.scene, this.camera);
                
                // 启用自适应质量
                this.performanceManager.setAdaptiveQuality(true);
            }
            
            setupControls() {
                // 阴影切换
                document.getElementById('toggle-shadows').addEventListener('click', () => {
                    this.renderer.shadowMap.enabled = !this.renderer.shadowMap.enabled;
                    this.updateUI();
                });
                
                // 自适应切换
                document.getElementById('toggle-adaptive').addEventListener('click', () => {
                    const isAdaptive = this.performanceManager.optimizations.adaptiveQuality;
                    this.performanceManager.setAdaptiveQuality(!isAdaptive);
                    this.updateUI();
                });
                
                // 强制低质量
                document.getElementById('force-low').addEventListener('click', () => {
                    this.performanceManager.setQualityLevel('low');
                    this.updateUI();
                });
                
                // 强制高质量
                document.getElementById('force-high').addEventListener('click', () => {
                    this.performanceManager.setQualityLevel('high');
                    this.updateUI();
                });
                
                // 重置性能
                document.getElementById('reset-performance').addEventListener('click', () => {
                    this.performanceManager.setQualityLevel('auto');
                    this.performanceManager.setAdaptiveQuality(true);
                    this.updateUI();
                });
                
                // 窗口大小变化
                window.addEventListener('resize', () => {
                    this.camera.aspect = window.innerWidth / window.innerHeight;
                    this.camera.updateProjectionMatrix();
                    this.renderer.setSize(window.innerWidth, window.innerHeight);
                });
            }
            
            updateUI() {
                if (!this.performanceManager) return;
                
                const report = this.performanceManager.getPerformanceReport();
                
                // 更新FPS显示
                const fpsElement = document.getElementById('fps');
                fpsElement.textContent = report.fps;
                fpsElement.className = 'metric-value';
                if (report.fps < 30) fpsElement.classList.add('critical');
                else if (report.fps < 45) fpsElement.classList.add('warning');
                
                // 更新其他指标
                document.getElementById('frame-time').textContent = report.frameTime + 'ms';
                document.getElementById('draw-calls').textContent = report.drawCalls;
                document.getElementById('triangles').textContent = report.triangles;
                document.getElementById('performance-level').textContent = report.performanceLevel;
                document.getElementById('shadows').textContent = report.shadowsEnabled ? '启用' : '禁用';
                document.getElementById('pixel-ratio').textContent = report.pixelRatio.toFixed(2);
            }
            
            animate() {
                requestAnimationFrame(() => this.animate());
                
                // 更新性能管理器
                if (this.performanceManager) {
                    this.performanceManager.update();
                }
                
                // 旋转测试对象
                this.testObjects.forEach((obj, index) => {
                    obj.rotation.x += 0.01 * (index % 3 + 1);
                    obj.rotation.y += 0.01 * (index % 2 + 1);
                });
                
                // 更新控制器
                this.controls.update();
                
                // 渲染场景
                this.renderer.render(this.scene, this.camera);
                
                // 更新UI（每30帧更新一次）
                if (this.performanceManager && this.performanceManager.frameCount % 30 === 0) {
                    this.updateUI();
                }
            }
        }
        
        // 启动性能测试
        new PerformanceTest();
    </script>
</body>
</html>